//
//  ActivityDetailViewController.m
//  OrderSeat
//
//  Created by 王威 on 13-11-26.
//  Copyright (c) 2013年 wangwei. All rights reserved.
//

#import "ActivityDetailViewController.h"
#import "UIImageView+WebCache.h"
#import "UseShopCell.h"
#import "SimpleCommentsCell.h"
#import "ShopHomeViewController.h"
#import "ComposeViewController.h"
#import "CommentsViewController.h"
#import "LoginViewController.h"

#define View1 [_theScrollview viewWithTag:1001]
#define View2 [_theScrollview viewWithTag:1002]
#define View3 [_theScrollview viewWithTag:1003]

#define BTN_LIKE_TAG 4001
#define BTN_FAV_TAG 4002
#define BTN_SHARE_TAG 4003
#define BTN_COMPOST_TAG 4004
#define SHOP_CELL_HEIGHT 48

#define LIKE_FORMAT @" 喜欢 (%@)"
#define FAV_FORMAT @" 收藏 (%@)"
#define SHARE_FORMAT @" 分享 (%@)"
#define USE_SHOP_FORMAT @"  可使用门店%d家"
#define COM_COUNT_FORMAT @"  有%d个评论"

@implementation ActivityDetailViewController

- (id)initWithActivityId:(NSString*)activityId
{
    self = [super initWithNibClass:[ActivityDetailViewController class]];
    if (self) {
        self.activityId = activityId;
        _photoList = [[NSMutableArray alloc] initWithCapacity:1];
        _dataSource = [[ActivityDetailDataSource alloc] initWithVC:self];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setupUI];
}

#pragma 隐藏tabbar
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[AppDelegate sharedInstance] hideTabBar:self.tabBarController];
    
    if (!self.isLoaded || self.isBack) {
        [_dataSource fetchActivityInfo];
        [self reset];
    }
}

- (void)setupUI
{
    [self createLeftButton];
    [self setNavigationTitle:@"活动详情"];
    
    _commentsTable.delegate = _dataSource;
    _commentsTable.dataSource = _dataSource;
    
    [UIView hiddensYES:@[_theScrollview]];
    [UIView drawBorders:@[View1, View2, View3, _commentsTable]];
    
    _theScrollview.height = ScreenHeight-NavBarHeight-StatusBarHeight;
}

- (void)leftButtonClick:(id)sender
{
    [[AppDelegate sharedInstance] showTabBar:self.tabBarController];
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)buttonAction:(id)sender
{
    if (![self checkFormForTag:[sender tag]])return;
    
    if ([sender tag] == BTN_LIKE_TAG) {
        [_dataSource like];
    }
    if ([sender tag] == BTN_SHARE_TAG) {
        [_dataSource share];
    }
    if ([sender tag] == BTN_COMPOST_TAG) {
        [self compostAction];
    }
}

- (BOOL)checkFormForTag:(int)tag
{
    if (tag == BTN_LIKE_TAG && _likeBtn.selected) {
        [AppDelegate showMessage:@"亲，每天只能喜欢一次吆"];
        return NO;
    }
    if (tag == BTN_FAV_TAG && ![AppDelegate checkLoginWithDelegate:self]) {
        return NO;
    }
    if (tag == BTN_FAV_TAG && _joinBtn.enabled) {
        [AppDelegate showMessage:@"亲，您已经参与过了"];
        return NO;
    }
    
    return YES;
}

- (void)compostAction
{
    if(![AppDelegate checkLoginWithDelegate:self]) return;
    
    ComposeViewController *compostVC = [[ComposeViewController alloc] initWithId:_activityId forType:Activity];
    compostVC.parentVC = self;
    [self.navigationController pushViewController:compostVC animated:YES];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    LoginViewController *loginVC = [[LoginViewController alloc] init];
    loginVC.backController = self;
    [self pushViewController:loginVC];
}

- (void)orderAction:(NSString *)shopId
{
    ShopHomeViewController *shopHomeVC = [[ShopHomeViewController alloc] initWithId:shopId];
    [self.navigationController pushViewController:shopHomeVC animated:YES];
}

- (IBAction)joinAction:(id)sender
{
    if(![AppDelegate checkLoginWithDelegate:self]) return;
    
    [_dataSource joinActivity];
}

- (void)opration:(OprationType)type count:(NSString*)count
{
    if (type == Like) {
        NSString *likeText = [NSString stringWithFormat:LIKE_FORMAT,count];
        [_likeBtn setTitleForNormal:likeText];
        _likeBtn.selected = YES;
        
        [[DbManager sharedManager] insertLike:_activityId type:ActivityLikeType];
    }
}

- (void)setFormValues:(NSDictionary*)dic
{
    NSLog(@"%@",dic);
    self.data = [NSMutableDictionary dictionaryWithDictionary:dic];
    NSString *imageURL = [dic objectForKey:@"image"];
    NSString *likeCount = [dic objectForKey:@"xihuan"];
    NSString *shareCount = [dic objectForKey:@"fenxiang"];
    NSString *downCount = [dic objectForKey:@"canyushu"];
    NSString *explain = [dic objectForKey:@"shuoming"];
    NSString *startTime = [dic objectForKey:@"strat_time"];
    NSString *endTime = [dic objectForKey:@"end_time"];
    NSString *useTime = [NSString stringWithFormat:@"%@-%@",startTime,endTime];
    
    int commCount = [[dic objectForKey:@"dianpingshu"] intValue];
    NSString *commentText = [NSString stringWithFormat:COM_COUNT_FORMAT,commCount];
    
    BOOL isFav = [[dic objectForKey:@"ifshoucang"] intValue] > 0;
    
    NSString *likeText = [NSString stringWithFormat:LIKE_FORMAT,likeCount];
    NSString *shareText = [NSString stringWithFormat:SHARE_FORMAT,shareCount];
    
    [_logoImage setImageWithURL:[NSURL URLWithString:imageURL]];
    [_logoImage addTarget:self action:@selector(ImageTapped:)];
    
    _titleLabel.text = [dic objectForKey:@"title"];
    _activityTimeLabel.text = useTime;
    _commentCountLabel.text = commentText;
    _joinCountLabel.text = downCount;
    _explainLabel.text = explain;
    
    if (isFav) {
        _joinBtn.enabled = !isFav;
        [_joinBtn setTitleForDisabled:@"已参与过"];
    }
    if (_isUse) {
        _joinBtn.enabled = !self.isUse;
        [_joinBtn setTitleForDisabled:@"活动已过期"];
    }
    
    [_likeBtn setTitleForNormal:likeText];
    [_shareBtn setTitleForNormal:shareText];
    _likeBtn.selected = [[DbManager sharedManager] isLike:_activityId type:ActivityLikeType];
    
    [_commentsTable reloadData];
    [_commentsTable addTarget:self action:@selector(viewCommentsAction:)];
    [self reLayoutSubviews];
}

- (void)viewCommentsAction:(id)sender
{
    CommentsViewController *commVC = [[CommentsViewController alloc] initWithId:_activityId andType:ActivityCommType];
    [self.navigationController pushViewController:commVC animated:YES];
}

#pragma 使用UIView扩展方法实现自动布局，自动计算视图高度
- (void)reLayoutSubviews
{
    [UIView hiddenNO:@[_theScrollview]];
    [UIView autoLabelSizeWithViews:@[_titleLabel,_explainLabel,_joinCountLabel]];
    
    _likeBtn.top = _shareBtn.top = _titleLabel.bottom_5;
    
    [UIView autoLayoutHorizontal:@[_joinCountLabel,_joinCountEndLabel]];
    [UIView autoHeights:@[View1, View3, _commentsTable]];
    [UIView autoLayoutVertical:@[View1,_joinBtn,View2,View3,_commentsTable]];
    
    [_theScrollview autoHeight];
}

- (void)shareWithData:(NSDictionary *)data
{
    NSString *content = [data objectForKey:@"content"];
    NSString *imageURL = [data objectForKey:@"image"];
    NSString *fxLink = [data objectForKey:@"fxlink"];
    
    [AppDelegate shareWithContent:content andImageURL:imageURL andLink:fxLink];
}

- (void)ImageTapped:(id)sender
{
    NSString *url = [self.data objectForKey:@"image"];
    NSString *content = [self.data objectForKey:@"shuoming"];
    
    MWPhoto *photo = [MWPhoto photoWithURL:[NSURL URLWithString:url]];
    photo.caption = content;
    [_photoList addObject:photo];
    
    MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
    browser.displayActionButton = NO;
    browser.displayNavArrows = YES;
    browser.displaySelectionButtons = NO;
    browser.alwaysShowControls = NO;
    browser.wantsFullScreenLayout = YES;
    browser.zoomPhotosToFill = YES;
    browser.enableGrid = NO;
    browser.startOnGrid = NO;
    [browser setCurrentPhotoIndex:0];
    
    UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:browser];
    nc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentModalViewController:nc animated:YES];
}

#pragma mark - MWPhotoBrowserDelegate
- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return 1;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    if (index < _photoList.count)
        return [_photoList objectAtIndex:index];
    return nil;
}

@end

//==========================================================================================
#pragma ===================数据源类实现=======================================================
//==========================================================================================

@implementation ActivityDetailDataSource

#define SHOP_TABLE_TAG 2001
#define COMMENTS_TABLE_TAG 2002
#define FETCH_ACTIVITY_TAG 3001
#define JOIN_ACTIVITY_TAG 3002
#define ACTIVITY_LIKE_TAG 3003
#define ACTIVITY_FAVORITES_TAG 3004
#define ACTIVITY_SHARE_TAG 3005
#define SimpleCommentsCellId    @"SimpleCommentsCell"
#define UseShopCellId           @"UseShopCell"

- (id)initWithVC:(id)viewController
{
    self = [super init];
    if (self) {
        self.viewController = viewController;
        _commentsList = [[NSMutableArray alloc] initWithCapacity:5];
        self.commentCell = [_viewController createCellWithNib:SimpleCommentsCellId];
    }
    return self;
}

- (void)fetchActivityInfo
{
    [SVProgressHUD show];
    NSString *url = [NSString stringWithFormat:API_ACTIVITY_INFO,_viewController.activityId,[AppSetting userName]];
    [self get:url tag:FETCH_ACTIVITY_TAG];
}

- (void)joinActivity
{
    [SVProgressHUD show];
    NSString *url = [NSString stringWithFormat:API_ACTIVITY_FAV,_viewController.activityId,[AppSetting userName]];
    [self get:url tag:JOIN_ACTIVITY_TAG];
}

- (void)like
{
    [SVProgressHUD show];
    NSString *url = [NSString stringWithFormat:API_ACTIVITY_LIKE, _viewController.activityId];
    [self get:url tag:ACTIVITY_LIKE_TAG];
}

- (void)share
{
    NSString *url = [NSString stringWithFormat:API_ACTIVITY_SHARE, _viewController.activityId];
    [self get:url tag:ACTIVITY_SHARE_TAG];
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    CLog(@"request: %@", request.responseString);
    
    NSDictionary *json = [request.responseString JSONValue];
    NSDictionary *data = [json objectForKey:@"data"];
    
    if (request.tag == FETCH_ACTIVITY_TAG) {
        self.commentsList = [data objectForKey:@"pinglun"];
        [self.viewController setFormValues:data];
        [SVProgressHUD dismiss];
    }
    
    if (request.tag == JOIN_ACTIVITY_TAG) {
        int state = [[data objectForKey:@"state"] intValue];
        if (state == 1) {
            [SVProgressHUD dismissWithSuccess:@"参与成功！"];
        }
        else if(state == 2) {
            [SVProgressHUD dismissWithSuccess:@"您已经参与过了！"];
        }
    }
    
    if (request.tag == ACTIVITY_LIKE_TAG) {
        int state = [[data objectForKey:@"state"] intValue];
        if (state == 1) {
            NSString *likeCount = [data objectForKey:@"xihuan"];
            [_viewController opration:Like count:likeCount];
            [SVProgressHUD dismiss];
        }
    }
    
    if (request.tag == ACTIVITY_SHARE_TAG) {
        [_viewController shareWithData:data];
    }
}

#pragma ===================加载tableview数据 Begin=================================

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [_commentCell getCellHeight:[_commentsList objectAtIndex:indexPath.row]];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _commentsList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SimpleCommentsCell *cell = [self.viewController createCellWithNib:SimpleCommentsCellId tableview:tableView];
    
    [cell setContent:[_commentsList objectAtIndex:indexPath.row]];
    
    return cell;
}

#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}


@end